def DFS(Adj):
    for u in V:
        if d[u] is None:
            DFS_visit(u)

def DFS_visit(u):
    d[u]='visited'
    for v in Adj[u]:
        if d[v] is None:
            DFS_visit(v)
    result.insert(0,u) #insert in front

if __name__=='__main__':
    Adj=[[1,7],[2,7],[5],[2,4],[5],[],[7],[],[]]#graph on CLRS pp.550
    V=xrange(len(Adj))
    d=[None]*len(Adj)
    result=[]

    print 'Adj:', Adj
    DFS(Adj)
    print 'result:', result
    

